package 二分查找;

public class 搜索二维矩阵 {
    public boolean searchMatrix1(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[] ints = new int[m * n];
        //将二维转化成一维
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                ints[n*i+j]=matrix[i][j];
            }
        }
        int left=0,right=m*n-1;
        while (left<=right){
            int mid = left+(right-left)/2;
            if (ints[mid]==target)
                return true;
            else if (ints[mid]>target){
                right=mid-1;
            }
            else if (ints[mid]<target){
                left = mid+1;
            }
        }
        return false;
    }
    //从右上角开始搜索
    public boolean searchMatrix2(int[][] matrix, int target) {
        if(matrix.length == 0)
            return false;
        int row = 0, col = matrix[0].length-1;
        while(row < matrix.length && col >= 0){
            if(matrix[row][col] < target)
                row++;
            else if(matrix[row][col] > target)
                col--;
            else
                return true;
        }
        return false;
    }
    public boolean searchMatrix3(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length;
        int low = 0, high = m * n - 1;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            //转化成二维对应的数字
            int x = matrix[mid / n][mid % n];
            if (x < target) {
                low = mid + 1;
            } else if (x > target) {
                high = mid - 1;
            } else {
                return true;
            }
        }
        return false;
    }
}
